package com.buildings.activity.table;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.buildings.R;
import com.buildings.activity.LoginActivity;
import com.buildings.activity.MainTabActivity;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.base.BaseActivity;
import com.buildings.base.BaseApplication;
import com.buildings.base.JsonBean;
import com.buildings.bean.AddressBean;
import com.buildings.bean.DivisionResultBean;
import com.buildings.bean.FaultTypeBean;
import com.buildings.bean.GeologicalSvyPlanningPtEntity;
import com.buildings.bean.LoginBean;
import com.buildings.bean.StratigraphySvyPointDbEntity;
import com.buildings.bean.TanCaodianDbEntity;
import com.buildings.bean.TanCaodianEntity;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.buildings.util.DataUtils;
import com.buildings.util.DialogUtils;
import com.buildings.util.FileUtil;
import com.buildings.util.GetAddressUtil;
import com.buildings.util.HYDialogUtils;
import com.buildings.util.HYImageUtils;
import com.buildings.util.PhotoRecycleBuild;
import com.buildings.util.SPUtil;
import com.buildings.util.StringUtil;
import com.google.gson.Gson;
import com.zr.earthquate.db.greendao.DaoSession;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;

import butterknife.BindView;
import okhttp3.Call;

//探槽点
public class TanCaodianActivity extends BaseActivity implements View.OnClickListener {
    private ImageView ivBack;
    private TextView tvTitle, tvRightText;
    //省
    private EditText etProvince;
    //市
    private EditText etCity;
    //区
    private EditText etArea;
    //经度
    private EditText etLat;
    //纬度
    private EditText etLon;
    //建筑地址
    private EditText etBuildingAddress;
    //探槽编号
    private EditText etTcid;
    //所属地质调查工程编号
    private EditText etGeologysvyprojectid;
    //野外编号
    private EditText etFieldid;
    //目标断层编号
    private EditText etTargetfaultid;
    //目标断层来源
    private TextView tv_targetfaultsource;
    //目标断层名称
    private EditText et_targetfaultname;
    //探槽名称
    private EditText et_name;
    //探槽来源与类型
    private TextView tv_trenchsource;
    //收集探槽来源补充说明
    private EditText et_collectedtrenchsource;
    //高程 [米]
    private EditText et_elevation;
    //探槽方向角度
    private EditText et_trenchdip;
    //参考位置
    private EditText et_locationname;
    //地貌环境
    private EditText et_geomophenv;
    //环境照片图像编号
    private EditText et_photoAiid;
    //照片镜向
    private TextView et_photoviewingto;
    //拍摄者
    private EditText et_photographer;
    //探槽长 [米]:
    private EditText et_length;
    //探槽宽
    private EditText et_width;
    //探槽深
    private EditText et_depth;
    //揭露地层数
    private EditText et_exposedstratumcount;
    //古地震事件次数
    private EditText et_eqeventcount;
    //最晚古地震发震时代
    private EditText et_latesteqperoidest;
    //最晚古地震发震时代误差
    private EditText et_latesteqperoider;
    //采集样品总数
    private EditText et_collectedsamplecount;
    //送样总数
    private EditText et_samplecount;
    //获得结果的样品数
    private EditText et_datingsamplecount;
    //符号或标注旋转角度
    private EditText et_lastangle;
    //探槽描述
    private EditText et_commentinfo;
    //相册图片
    private RecyclerView rvPics;
    //探槽方向角度 [度] 提示
    private ImageView ivTrenchdioHint;
    //是否隐藏按钮
    private TextView tv_visibile;
    //隐藏的布局
    private LinearLayout ll_visibile;
    PhotoRecycleBuild photoRecycleBuild;
    private ImageView ivIdHint;
    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTY = "county";

    private List<DivisionResultBean.Division> provinceList;
    private List<DivisionResultBean.Division> cityList;
    private List<DivisionResultBean.Division> countyList;
    private AddressBean province;
    private AddressBean.CityBean city;
    private String county;

    private Dialog myDialog;

    //断层性质数据
    private List<FaultTypeBean.DataBean> dataBeans = new ArrayList<>();

    private FaultTypeBean.DataBean trenchTypeCVDBean;
    private FaultTypeBean.DataBean directionBean;
    private FaultTypeBean.DataBean FaultSourceCVDBean;

    private DaoSession daoSession;
    Button btnSubmit;
    private long _id = -1;
    private String urlArr;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tancaodian);
        initView();
    }

    private int joninType;
    private String uuid;

    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        btnSubmit = findViewById(R.id.btn_submit);
        tvTitle = findViewById(R.id.tv_title);
        tvRightText = findViewById(R.id.tv_right_text);
        etProvince = findViewById(R.id.et_province);
        etCity = findViewById(R.id.et_city);
        etArea = findViewById(R.id.et_area);
        etLat = findViewById(R.id.et_lat);
        etLon = findViewById(R.id.et_lon);
        ll_visibile = findViewById(R.id.ll_visibile);
        tv_visibile = findViewById(R.id.tv_visibile);
        tv_trenchsource = findViewById(R.id.tv_trenchsource);
        ivTrenchdioHint = findViewById(R.id.iv_trenchdio_hint);
        et_elevation = findViewById(R.id.et_elevation);
        etTcid = findViewById(R.id.et_tcid);
        etFieldid = findViewById(R.id.et_fieldid);
        et_name = findViewById(R.id.et_name);
        et_depth = findViewById(R.id.et_depth);
        et_width = findViewById(R.id.et_width);
        rvPics = findViewById(R.id.rv_pics);
        et_commentinfo = findViewById(R.id.et_commentinfo);
        et_lastangle = findViewById(R.id.et_lastangle);
        et_samplecount = findViewById(R.id.et_samplecount);
        et_datingsamplecount = findViewById(R.id.et_datingsamplecount);
        et_collectedsamplecount = findViewById(R.id.et_collectedsamplecount);
        et_latesteqperoider = findViewById(R.id.et_latesteqperoider);
        et_length = findViewById(R.id.et_length);
        et_latesteqperoidest = findViewById(R.id.et_latesteqperoidest);
        et_eqeventcount = findViewById(R.id.et_eqeventcount);
        et_photographer = findViewById(R.id.et_photographer);
        et_photoviewingto = findViewById(R.id.et_photoviewingto);
        et_photoAiid = findViewById(R.id.et_photoAiid);
        et_geomophenv = findViewById(R.id.et_geomophenv);
        et_exposedstratumcount = findViewById(R.id.et_exposedstratumcount);
        et_locationname = findViewById(R.id.et_locationname);
        et_trenchdip = findViewById(R.id.et_trenchdip);
        et_collectedtrenchsource = findViewById(R.id.et_collectedtrenchsource);
        tv_targetfaultsource = findViewById(R.id.tv_targetfaultsource);
        et_targetfaultname = findViewById(R.id.et_targetfaultname);
        etTargetfaultid = findViewById(R.id.et_targetfaultid);
        etGeologysvyprojectid = findViewById(R.id.et_geologysvyprojectid);
        etBuildingAddress = findViewById(R.id.et_building_address);
        ivIdHint = findViewById(R.id.iv_id_hint);
        ivBack.setOnClickListener(this);
        tvRightText.setOnClickListener(this);
        tv_trenchsource.setOnClickListener(this);
        etProvince.setOnClickListener(this);
        etCity.setOnClickListener(this);
        tv_visibile.setOnClickListener(this);
        etArea.setOnClickListener(this);
        ivTrenchdioHint.setOnClickListener(this);
        tv_targetfaultsource.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        et_photoviewingto.setOnClickListener(this);
        ivIdHint.setOnClickListener(this);
        joninType = getIntent().getIntExtra("joninType", 1);
        daoSession = BaseApplication.getInstance().getDaoSession();
        photoRecycleBuild = new PhotoRecycleBuild(this, rvPics, joninType);
        if (joninType != 2) {
            tvTitle.setText("探槽-点");
            tvRightText.setText("保存");
            double x = getIntent().getDoubleExtra("x", 0.0);
            double y = getIntent().getDoubleExtra("y", 0.0);
            type = getIntent().getStringExtra("type");
            taskId = getIntent().getStringExtra("taskId");
            projectId = getIntent().getStringExtra("projectId");
            projectName = getIntent().getStringExtra("projectName");
            taskName = getIntent().getStringExtra("taskName");
            isOnline = getIntent().getBooleanExtra("isOnLine", true);
            if (TextUtils.isEmpty(type)) {
                finish();
            }
            if (isOnline && TextUtils.isEmpty(taskId)){
                finish();
            }
            if (isOnline && TextUtils.isEmpty(projectId)){
                finish();
            }
            etLat.setText(x + "");
            etLon.setText(y + "");
            String province = new GetAddressUtil(activity).getProvince(x, y);
            etProvince.setText(province);
            String city = new GetAddressUtil(activity).getCity(x, y);
            etCity.setText(city);
            String area = new GetAddressUtil(activity).getArea(x, y);
            etArea.setText(area);
            setBuildingAddress();
            if (getIntent().hasExtra("_id")) {
                _id = getIntent().getLongExtra("_id", -1);
                setLocalData(_id);
            }
            if (1 == Constant.IS_ON_LINE){
                btnSubmit.setVisibility(View.VISIBLE);
            }else {
                btnSubmit.setVisibility(View.GONE);
            }
        } else {
            isOnline = getIntent().getBooleanExtra("isOnLine", false);
            if (1 == Constant.IS_ON_LINE){
                tvTitle.setText("探槽-点详情");
                uuid = getIntent().getStringExtra("uuid");
                setEnableFalse();
                getDetailHttp();
                btnSubmit.setVisibility(View.GONE);
            }else {
                tvTitle.setText("探槽-点");
                tvRightText.setText("保存");
                uuid = getIntent().getStringExtra("uuid");
                if (getIntent().hasExtra("_id")) {
                    _id = getIntent().getLongExtra("_id", -1);
                    setLocalData(_id);
                }
                btnSubmit.setVisibility(View.GONE);
            }
        }
    }

    public void setLocalData(long a) {
        if (a == -1) {
            return;
        }
        List<TanCaodianDbEntity> students = daoSession.loadAll(TanCaodianDbEntity.class);
        for (TanCaodianDbEntity tanCaodianDbEntity : students) {
            if (a == tanCaodianDbEntity.get_id()) {
                setDetail(tanCaodianDbEntity);
            }
        }
    }

    private void setEnableFalse() {
        etTcid.setEnabled(false);
        et_name.setEnabled(false);
        et_elevation.setEnabled(false);
        et_trenchdip.setEnabled(false);
        etProvince.setEnabled(false);
        etCity.setEnabled(false);
        etArea.setEnabled(false);
        etLon.setEnabled(false);
        etLat.setEnabled(false);
        et_lastangle.setEnabled(false);
        et_photoviewingto.setEnabled(false);
        etBuildingAddress.setFocusable(false);
        et_collectedtrenchsource.setEnabled(false);
        etGeologysvyprojectid.setEnabled(false);
        etFieldid.setEnabled(false);
        etTargetfaultid.setEnabled(false);
        tv_targetfaultsource.setEnabled(false);
        et_targetfaultname.setEnabled(false);
        tv_trenchsource.setEnabled(false);
        et_locationname.setEnabled(false);
        et_geomophenv.setEnabled(false);
        et_photoAiid.setEnabled(false);
        et_photographer.setEnabled(false);
        et_length.setEnabled(false);
        et_width.setEnabled(false);
        et_depth.setEnabled(false);
        et_exposedstratumcount.setEnabled(false);
        et_eqeventcount.setEnabled(false);
        et_latesteqperoidest.setEnabled(false);
        et_latesteqperoider.setEnabled(false);
        et_collectedsamplecount.setEnabled(false);
        et_samplecount.setEnabled(false);
        et_datingsamplecount.setEnabled(false);
        et_commentinfo.setEnabled(false);
    }

    public void setBuildingAddress() {
        if (TextUtils.isEmpty(etLat.getText().toString().trim())) {
            return;
        }
        if (TextUtils.isEmpty(etLon.getText().toString().trim())) {
            return;
        }
        double lat = Double.parseDouble(etLat.getText().toString().trim());
        double lon = Double.parseDouble(etLon.getText().toString().trim());
        String address = new GetAddressUtil(activity).getAddress(lat,lon);
        etBuildingAddress.setText(address);
    }
    private String type;
    private String taskId = "";
    private String projectId = "";
    private String projectName = "";
    private String taskName = "";
    private boolean isOnline;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_targetfaultsource:
                FaultTypeBean faultTypeBean1 = new Gson().fromJson(JsonBean.FaultSourceCVD, FaultTypeBean.class);
                setFaultTypeCVD(faultTypeBean1, "FaultSourceCVD");
                break;
            case R.id.et_photoviewingto:
                FaultTypeBean faultTypeBean2 = new Gson().fromJson(JsonBean.CVD_16_Direction, FaultTypeBean.class);
                setFaultTypeCVD(faultTypeBean2, "CVD-16-Direction");
                break;
            case R.id.tv_visibile:
                ll_visibile.setVisibility(View.GONE);
                if (ll_visibile.getVisibility() == View.VISIBLE) {
                } else {
                    ll_visibile.setVisibility(View.VISIBLE);
                }
                if (ll_visibile.getVisibility() == View.VISIBLE) {
                    tv_visibile.setText("显示更多");
                } else {
                    tv_visibile.setText("隐藏更多");
                }
                break;
            case R.id.et_province:
                getDivisions("root", PROVINCE);
                break;
            case R.id.iv_trenchdio_hint:
                HYDialogUtils.showCommonAlertDialog(this, "最小值: 0\n" +
                                "最大值: 359"
                        , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                            }
                        });
                break;
            case R.id.tv_trenchsource:
                FaultTypeBean faultTypeBean3 = new Gson().fromJson(JsonBean.TrenchTypeCVD, FaultTypeBean.class);
                setFaultTypeCVD(faultTypeBean3, "TrenchTypeCVD");
                break;
            case R.id.et_city:
                if (TextUtils.isEmpty(etProvince.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择省");
                    return;
                }
                getDivisions("", CITY);
                break;
            case R.id.et_area:
                if (TextUtils.isEmpty(etProvince.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择省");
                    return;
                }
                if (TextUtils.isEmpty(etCity.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择市");
                    return;
                }
                getDivisions("", COUNTY);
                break;
            case R.id.tv_right_text:
                //TODO 调用保存表单接口
                save();
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.iv_id_hint:
                HYDialogUtils.showCommonAlertDialog(this, "长度17位，前9位，行政区划代码6位+3位专题号，后8位自定义编码，字母数字均可，不足8位#补齐\n" +
                                "3位专题号，用户自己设置。一般就是100，101，102...,201,202"
                        , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                            }
                        });
                break;
        }
    }

    private void save() {
        TanCaodianDbEntity tanCaodianDbEntity = new TanCaodianDbEntity();
        String province = etProvince.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        String area = etArea.getText().toString().trim();
        String lat = etLon.getText().toString().trim();
        String lon = etLat.getText().toString().trim();
        String lastangle = et_lastangle.getText().toString().trim();
        String photoviewingto = et_photoviewingto.getText().toString().trim();
        String buildingAddress = etBuildingAddress.getText().toString().trim();

        String tcid = etTcid.getText().toString().trim();
        String name = et_name.getText().toString().trim();
        String elevation = et_elevation.getText().toString().trim();
        String trenchdip = et_trenchdip.getText().toString().trim();
        String collectedtrenchsource = et_collectedtrenchsource.getText().toString().trim();
        String geologysvyprojectid = etGeologysvyprojectid.getText().toString().trim();
        String fieldid = etFieldid.getText().toString().trim();
        String targetfaultid = etTargetfaultid.getText().toString().trim();
        String targetfaultsource = tv_targetfaultsource.getText().toString().trim();
        String targetfaultname = et_targetfaultname.getText().toString().trim();
        String trenchsource = tv_trenchsource.getText().toString().trim();
        String locationname = et_locationname.getText().toString().trim();
        String geomophenv = et_geomophenv.getText().toString().trim();
        String photoAiid = et_photoAiid.getText().toString().trim();
        String photographer = et_photographer.getText().toString().trim();
        String length = et_length.getText().toString().trim();
        String width = et_width.getText().toString().trim();
        String depth = et_depth.getText().toString().trim();
        String exposedstratumcount = et_exposedstratumcount.getText().toString().trim();
        String eqeventcount = et_eqeventcount.getText().toString().trim();
        String latesteqperoidest = et_latesteqperoidest.getText().toString().trim();
        String latesteqperoider = et_latesteqperoider.getText().toString().trim();
        String collectedsamplecount = et_collectedsamplecount.getText().toString().trim();
        String samplecount = et_samplecount.getText().toString().trim();
        String datingsamplecount = et_datingsamplecount.getText().toString().trim();
        String commentinfo = et_commentinfo.getText().toString().trim();
        if (TextUtils.isEmpty(province)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(city)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(lon)) {
            Toast("请录入纬度");
            return;
        }
        if (TextUtils.isEmpty(lat)) {
            Toast("请录入经度");
            return;
        }
        if (TextUtils.isEmpty(buildingAddress)) {
            Toast("请录入详细地址");
            return;
        }
        if (TextUtils.isEmpty(tcid)) {
            Toast("探槽不能为空");
            return;
        }
        if (tcid.length() != 17) {
            Toast("请录入正确的探槽id");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            Toast("探槽名称不能为空");
            return;
        }
        if (TextUtils.isEmpty(elevation)) {
            Toast("请录入高程数据");
            return;
        }
        if (TextUtils.isEmpty(trenchdip)) {
            Toast("请录入探槽方向角度");
            return;
        }
        tanCaodianDbEntity.setProvince(province);
        tanCaodianDbEntity.setCity(city);
        tanCaodianDbEntity.setArea(area);
        tanCaodianDbEntity.setLat(lat);
        tanCaodianDbEntity.setLon(lon);
        tanCaodianDbEntity.setTown(buildingAddress);
        tanCaodianDbEntity.setId(tcid);
        tanCaodianDbEntity.setName(name);
        tanCaodianDbEntity.setElevation(elevation);
        tanCaodianDbEntity.setLastangle(lastangle);
        tanCaodianDbEntity.setTrenchdip(trenchdip);
        tanCaodianDbEntity.setCollectedtrenchsource(collectedtrenchsource);
        tanCaodianDbEntity.setGeologysvyprojectid(geologysvyprojectid);
        tanCaodianDbEntity.setFieldid(fieldid);
        tanCaodianDbEntity.setTargetfaultid(targetfaultid);
        tanCaodianDbEntity.setTargetfaultsource(null == FaultSourceCVDBean ?
                null == tanCaodianDbEntity ? "" : tanCaodianDbEntity.getTargetfaultsource() : FaultSourceCVDBean.getDictItemCode());
        tanCaodianDbEntity.setTargetfaultsourceName(targetfaultsource);
        tanCaodianDbEntity.setTargetfaultname(targetfaultname);
        tanCaodianDbEntity.setTrenchsource(null == trenchTypeCVDBean ?
                null == tanCaodianDbEntity ? "" : tanCaodianDbEntity.getTrenchsource() : trenchTypeCVDBean.getDictItemCode());
        tanCaodianDbEntity.setTrenchsourceName(trenchsource);
        tanCaodianDbEntity.setLocationname(locationname);
        tanCaodianDbEntity.setGeomophenv(geomophenv);
        tanCaodianDbEntity.setPhotoAiid(photoAiid);
        tanCaodianDbEntity.setPhotoviewingto(null == directionBean ?
                null == tanCaodianDbEntity ? "" : tanCaodianDbEntity.getPhotoviewingto() : directionBean.getDictItemCode());
        tanCaodianDbEntity.setPhotoviewingtoName(photoviewingto);
        tanCaodianDbEntity.setPhotographer(photographer);
        tanCaodianDbEntity.setLength(length);
        tanCaodianDbEntity.setWidth(width);
        tanCaodianDbEntity.setDepth(depth);
        tanCaodianDbEntity.setExposedstratumcount(exposedstratumcount);
        tanCaodianDbEntity.setEqeventcount(eqeventcount);
        tanCaodianDbEntity.setLatesteqperoidest(latesteqperoidest);
        tanCaodianDbEntity.setLatesteqperoider(latesteqperoider);
        tanCaodianDbEntity.setCollectedsamplecount(collectedsamplecount);
        tanCaodianDbEntity.setSamplecount(samplecount);
        tanCaodianDbEntity.setDatingsamplecount(datingsamplecount);
        tanCaodianDbEntity.setCommentInfo(commentinfo);
        if (Constant.IS_ON_LINE == 1) {
            tanCaodianDbEntity.setProjectId(projectId);
            tanCaodianDbEntity.setProjectName(projectName);
            tanCaodianDbEntity.setTaskName(taskName);
            tanCaodianDbEntity.setTaskId(taskId);
        }
        if (photoRecycleBuild.getSrcList().size() != 0) {
            String url = "";
            for (int i = 0; i < photoRecycleBuild.getSrcList().size(); i++) {
                if (TextUtils.isEmpty(url)) {
                    url = FileUtil.uriToFile(photoRecycleBuild.getSrcList().get(i), activity).getPath();
                } else {
                    url = url + "," + FileUtil.uriToFile(photoRecycleBuild.getSrcList().get(i), activity).getPath();
                }
            }
            tanCaodianDbEntity.setExtends7(url);
        }
        if (-1 != _id) {
            tanCaodianDbEntity.set_id(_id);
        }
        daoSession.insertOrReplace(tanCaodianDbEntity);
        CustomToast.showToast(this, "保存成功");
        finish();
    }

    private void submit() {
        String tcid = etTcid.getText().toString().trim();
        String name = et_name.getText().toString().trim();
        String elevation = et_elevation.getText().toString().trim();
        String trenchdip = et_trenchdip.getText().toString().trim();
        String province = etProvince.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        String area = etArea.getText().toString().trim();
        String lat = etLon.getText().toString().trim();
        String lon = etLat.getText().toString().trim();
        String lastangle = et_lastangle.getText().toString().trim();
        String photoviewingto = et_photoviewingto.getText().toString().trim();
        String buildingAddress = etBuildingAddress.getText().toString().trim();
        String collectedtrenchsource = et_collectedtrenchsource.getText().toString().trim();
        String geologysvyprojectid = etGeologysvyprojectid.getText().toString().trim();
        String fieldid = etFieldid.getText().toString().trim();
        String targetfaultid = etTargetfaultid.getText().toString().trim();
        String targetfaultsource = tv_targetfaultsource.getText().toString().trim();
        String targetfaultname = et_targetfaultname.getText().toString().trim();
        String trenchsource = tv_trenchsource.getText().toString().trim();
        String locationname = et_locationname.getText().toString().trim();
        String geomophenv = et_geomophenv.getText().toString().trim();
        String photoAiid = et_photoAiid.getText().toString().trim();
        String photographer = et_photographer.getText().toString().trim();
        String length = et_length.getText().toString().trim();
        String width = et_width.getText().toString().trim();
        String depth = et_depth.getText().toString().trim();
        String exposedstratumcount = et_exposedstratumcount.getText().toString().trim();
        String eqeventcount = et_eqeventcount.getText().toString().trim();
        String latesteqperoidest = et_latesteqperoidest.getText().toString().trim();
        String latesteqperoider = et_latesteqperoider.getText().toString().trim();
        String collectedsamplecount = et_collectedsamplecount.getText().toString().trim();
        String samplecount = et_samplecount.getText().toString().trim();
        String datingsamplecount = et_datingsamplecount.getText().toString().trim();
        String commentinfo = et_commentinfo.getText().toString().trim();
        if (TextUtils.isEmpty(province)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(city)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(lon)) {
            Toast("请录入纬度");
            return;
        }
        if (TextUtils.isEmpty(lat)) {
            Toast("请录入经度");
            return;
        }
        if (TextUtils.isEmpty(buildingAddress)) {
            Toast("请录入详细地址");
            return;
        }
        if (TextUtils.isEmpty(tcid)) {
            Toast("探槽不能为空");
            return;
        }
        if (tcid.length() != 17) {
            Toast("请录入正确的探槽id");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            Toast("探槽名称不能为空");
            return;
        }
        if (TextUtils.isEmpty(elevation)) {
            Toast("请录入高程数据");
            return;
        }
        if (TextUtils.isEmpty(trenchdip)) {
            Toast("请录入探槽方向角度");
            return;
        }

        if (myDialog == null) {
            myDialog = DialogUtils.showRefreshDialog(activity);
        } else {
            myDialog.show();
        }

        DialogUtils.showIOSDialog(activity, "提示", "", "", "", ""
                , new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (null != myDialog)
                            myDialog.dismiss();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        submit();
                        photoRecycleBuild.submitImage(photoRecycleBuild.getSrcList(), 1, new PhotoRecycleBuild.ImageCallBack() {
                            @Override
                            public void onCallBack(String url) {
                                TanCaodianActivity.this.urlArr = url;

                                JsonBuilder jsonBuilder = new JsonBuilder(TanCaodianActivity.this);
                                jsonBuilder.put("province", province);
                                jsonBuilder.put("city", city);
                                jsonBuilder.put("area", area);
                                jsonBuilder.put("lat", lon);
                                jsonBuilder.put("lon", lat);
                                jsonBuilder.put("town", buildingAddress);
                                jsonBuilder.put("id", tcid);
                                jsonBuilder.put("name", name);
                                jsonBuilder.put("type", type);
                                jsonBuilder.put("taskId", taskId);
                                jsonBuilder.put("projectId", projectId);
                                jsonBuilder.put("projectName", projectName);
                                jsonBuilder.put("taskName", taskName);
                                jsonBuilder.put("userId", SPUtil.get("userId", ""));
                                jsonBuilder.put("elevation", elevation);
                                jsonBuilder.put("trenchdip", trenchdip);
                                jsonBuilder.put("fieldid", fieldid);
                                jsonBuilder.put("targetfaultname", targetfaultname);
                                jsonBuilder.put("trenchsource", null == trenchTypeCVDBean ? null == tanCaodianDbEntity ? "" : tanCaodianDbEntity.getTrenchsource() : trenchTypeCVDBean.getDictItemCode());
                                jsonBuilder.put("trenchsourceName", trenchsource);
                                jsonBuilder.put("locationname", locationname);
                                jsonBuilder.put("photoAiid", photoAiid);
                                //照片镜像
                                jsonBuilder.put("photoviewingto", null == directionBean ? null == tanCaodianDbEntity ? "" : tanCaodianDbEntity.getPhotoviewingto() : directionBean.getDictItemCode());
                                jsonBuilder.put("photoviewingtoName", photoviewingto);
                                jsonBuilder.put("photographer", photographer);
                                jsonBuilder.put("length", length);
                                jsonBuilder.put("width", width);
                                jsonBuilder.put("depth", depth);
                                jsonBuilder.put("exposedstratumcount", exposedstratumcount);
                                jsonBuilder.put("eqeventcount", eqeventcount);
                                jsonBuilder.put("collectedsamplecount", collectedsamplecount);
                                jsonBuilder.put("geologysvyprojectid", geologysvyprojectid);
                                jsonBuilder.put("targetfaultid", targetfaultid);
                                jsonBuilder.put("targetfaultsource", null == FaultSourceCVDBean ?
                                        null == tanCaodianDbEntity ? "" : tanCaodianDbEntity.getTargetfaultsource() : FaultSourceCVDBean.getDictItemCode());
                                jsonBuilder.put("targetfaultsourceName", targetfaultsource);
                                jsonBuilder.put("collectedtrenchsource", collectedtrenchsource);
                                jsonBuilder.put("geomophenv", geomophenv);
                                jsonBuilder.put("latesteqperoidest", latesteqperoidest);
                                jsonBuilder.put("latesteqperoider", latesteqperoider);
                                jsonBuilder.put("samplecount", samplecount);
                                jsonBuilder.put("datingsamplecount", datingsamplecount);
                                jsonBuilder.put("lastangle", lastangle);
                                jsonBuilder.put("commentinfo", commentinfo);
                                jsonBuilder.put("extends7", urlArr);
                                jsonBuilder.put("createUser", SPUtil.get("userId", ""));
                                MyHttpClient
                                        .newBuilder()
                                        .post()
                                        .url(Api.TCD_SAVE)
                                        .addParam(jsonBuilder.toJsonString())
                                        .build()
                                        .enqueue(new BaseCallBack<LoginBean>() {
                                            @Override
                                            public void onSuccess(LoginBean bean) {
                                                super.onSuccess(bean);
                                                if (bean.getCode() == 200) {
                                                    if (-1 != _id && null != tanCaodianDbEntity) {
                                                        try {
                                                            daoSession.delete(tanCaodianDbEntity);
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                    CustomToast.showToast(TanCaodianActivity.this, "提交成功");
                                                    finish();
                                                }
                                                if (myDialog != null)
                                                    myDialog.dismiss();
                                            }

                                            @Override
                                            public void onFailure(Call call, IOException e) {
                                                super.onFailure(call, e);
                                                if (myDialog != null)
                                                    myDialog.dismiss();
                                                CustomToast.showToast(TanCaodianActivity.this, "网络异常");
                                            }

                                            @Override
                                            public void onError(int code) {
                                                super.onError(code);
                                                if (myDialog != null)
                                                    myDialog.dismiss();
                                                CustomToast.showToast(TanCaodianActivity.this, "网络异常");
                                            }
                                        });
                            }
                        });
                    }
                }, "提交后不能再修改");
    }

    private void getDivisions(String divisionid, final String type) {
        String JsonData = DataUtils.getAddressJson(activity, "province.json");//获取assets目录下的json文件数据
        ArrayList<AddressBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        if (null == jsonBean || jsonBean.size() == 0) {
            Toast.makeText(activity, "地理位置获取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.equals(PROVINCE, type)) {
            showProvincePickerView(jsonBean, PROVINCE);
        } else if (TextUtils.equals(CITY, type)) {
            for (AddressBean addressBean : jsonBean) {
                if (addressBean.getName().equals(etProvince.getText().toString().trim())) {
                    showPickerView(addressBean.getCityList(), CITY);
                }
            }
        } else if (TextUtils.equals(COUNTY, type)) {
            for (AddressBean addressBean : jsonBean) {
                if (addressBean.getName().equals(etProvince.getText().toString().trim())) {
                    for (AddressBean.CityBean cityBean : addressBean.getCityList()) {
                        if (cityBean.getName().equals(etCity.getText().toString().trim())) {
                            showAreaPickerView(cityBean.getArea(), COUNTY);
                        }
                    }
                }
            }
        }
//        String url = Api.GET_LOCATION + "divisions/" + divisionid + "/subdivisions";
//        MyHttpClient
//                .newBuilder()
//                .get()
//                .url(url)
//                .build()
//                .enqueue(new BaseCallBack<DivisionResultBean>() {
//                    @Override
//                    public void onSuccess(DivisionResultBean divisionResultBean) {
//                        super.onSuccess(divisionResultBean);
//                        if (myDialog != null)
//                            myDialog.dismiss();
//                        if (divisionResultBean != null && divisionResultBean.getCode() == 200) {
//                            if (divisionResultBean.getData() != null) {
//                                if (TextUtils.equals(PROVINCE, type)) {
//                                    provinceList = divisionResultBean.getData();
//                                    showPickerView(provinceList, PROVINCE);
//                                } else if (TextUtils.equals(CITY, type)) {
//                                    cityList = divisionResultBean.getData();
//                                    showPickerView(cityList, CITY);
//                                } else if (TextUtils.equals(COUNTY, type)) {
//                                    countyList = divisionResultBean.getData();
//                                    showPickerView(countyList, COUNTY);
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        super.onFailure(call, e);
//                        CustomToast.showToast(activity, "网络异常");
//                        if (myDialog != null)
//                            myDialog.dismiss();
//                    }
//
//                    @Override
//                    public void onError(int code) {
//                        super.onError(code);
//                        CustomToast.showToast(activity, "网络异常");
//                        if (myDialog != null)
//                            myDialog.dismiss();
//                    }
//                });
    }

    private void showProvincePickerView(final List<AddressBean> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                AddressBean division = list.get(options1);
                switch (type) {
                    case PROVINCE:
                        province = division;
                        city = null;
                        etCity.setText("");
                        etProvince.setText(division.getName());
                        county = null;
                        etArea.setText("");
                        break;
                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    private void showAreaPickerView(final List<String> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String division = list.get(options1);
                county = division;
                etArea.setText(county);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    private void showPickerView(final List<AddressBean.CityBean> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                AddressBean.CityBean division = list.get(options1);
                switch (type) {
                    case CITY:
                        city = division;
                        county = null;
                        etArea.setText("");
                        etCity.setText(division.getName());
                        break;
                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case HYImageUtils.REQUEST_CODE_FROM_CAMERA:
                List<Uri> list_1 = new ArrayList<>();
                list_1.add(HYImageUtils.imageUriFromCamera);
                photoRecycleBuild.updataAdapter(list_1);
                break;
            case HYImageUtils.REQUEST_CODE_FROM_ALBUM:
                ArrayList<String> files = data.getStringArrayListExtra("files");
                if (files == null || files.size() == 0) {
                    return;
                }
                List<Uri> list_2 = new ArrayList<>();
                for (String file : files) {
                    list_2.add(Uri.fromFile(new File(file)));
                }
                photoRecycleBuild.updataAdapter(list_2);
                // submitImage(list_2, correctTypeListEntity.getFieldList().get(lastClickItemPosition));
                break;
        }
    }

    private void getHttpData(String type) {
        MyHttpClient
                .newBuilder()
                .get()
                .url(Api.DCGCD_TCD + type)
                .build()
                .enqueue(new BaseCallBack<FaultTypeBean>() {
                    @Override
                    public void onSuccess(FaultTypeBean bean) {
                        super.onSuccess(bean);
                        if (bean.getCode() == 200) {
                            setFaultTypeCVD(bean, type);
                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TanCaodianActivity.this, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TanCaodianActivity.this, "网络异常");
                    }
                });
    }


    public void setFaultTypeCVD(FaultTypeBean bean, String type) {
        dataBeans.clear();
        dataBeans.addAll(bean.getData());
        String[] arr = new String[dataBeans.size()];
        for (int i = 0; i < dataBeans.size(); i++) {
            arr[i] = dataBeans.get(i).getDictItemName();
        }
        HYDialogUtils.showSingleChoiceItemAlertDialog(this, "选择", 0, arr
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (type) {
                            case "FaultSourceCVD":
                                FaultSourceCVDBean = dataBeans.get(i);
                                tv_targetfaultsource.setText(dataBeans.get(i).getDictItemName());
                                break;
                            case "TrenchTypeCVD":
                                trenchTypeCVDBean = dataBeans.get(i);
                                tv_trenchsource.setText(dataBeans.get(i).getDictItemName());
                                break;
                            case "CVD-16-Direction":
                                directionBean = dataBeans.get(i);
                                et_photoviewingto.setText(dataBeans.get(i).getDictItemName());
                                break;
                        }
                        dialogInterface.dismiss();
                    }
                });
    }

    public void getDetailHttp() {
        if (myDialog == null) {
            myDialog = DialogUtils.showRefreshDialog(activity);
        } else {
            myDialog.show();
        }
        String url = Api.TCD_SAVE + "/" + uuid;
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                .build()
                .enqueue(new BaseCallBack<TanCaodianEntity>() {
                    @Override
                    public void onSuccess(TanCaodianEntity bean) {
                        super.onSuccess(bean);
                        if (bean.getCode() == 200) {
                            setDetailData(bean);
                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TanCaodianActivity.this, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TanCaodianActivity.this, "网络异常");
                    }
                });
    }

    private void setDetailData(TanCaodianEntity bean) {
        etProvince.setText(StringUtil.isNull(bean.getData().getProvince()));
        etCity.setText(StringUtil.isNull(bean.getData().getCity()));
        etArea.setText(StringUtil.isNull(bean.getData().getArea()));
        etLat.setText(StringUtil.isNull(bean.getData().getLat()));
        etLon.setText(StringUtil.isNull(bean.getData().getLon()));
        etBuildingAddress.setText(StringUtil.isNull(bean.getData().getTown()));

        etTcid.setText(StringUtil.isNull(bean.getData().getId()));
        et_name.setText(StringUtil.isNull(bean.getData().getName()));
        et_elevation.setText(StringUtil.isNull(bean.getData().getElevation()));
        et_trenchdip.setText(StringUtil.isNull(bean.getData().getTrenchdip()));
        et_lastangle.setText(StringUtil.isNull(bean.getData().getLastangle()));
        et_photoviewingto.setText(StringUtil.isNull(bean.getData().getPhotoviewingtoName()));
        et_collectedtrenchsource.setText(StringUtil.isNull(bean.getData().getCollectedtrenchsource()));
        etGeologysvyprojectid.setText(StringUtil.isNull(bean.getData().getGeologysvyprojectid()));
        etFieldid.setText(StringUtil.isNull(bean.getData().getFieldid()));
        etTargetfaultid.setText(StringUtil.isNull(bean.getData().getTargetfaultid()));
        tv_targetfaultsource.setText(StringUtil.isNull(bean.getData().getTargetfaultsource()));
        tv_targetfaultsource.setText(StringUtil.isNull(bean.getData().getTargetfaultsourceName()));
        et_targetfaultname.setText(StringUtil.isNull(bean.getData().getTargetfaultname()));
        tv_trenchsource.setText(StringUtil.isNull(bean.getData().getTrenchsourceName()));
        et_locationname.setText(StringUtil.isNull(bean.getData().getLocationname()));
        et_geomophenv.setText(StringUtil.isNull(bean.getData().getGeomophenv()));
        et_photoAiid.setText(StringUtil.isNull(bean.getData().getPhotoAiid()));
        et_photographer.setText(StringUtil.isNull(bean.getData().getPhotographer()));
        et_length.setText(StringUtil.isNull(bean.getData().getLength()));
        et_width.setText(StringUtil.isNull(bean.getData().getWidth()));
        et_depth.setText(StringUtil.isNull(bean.getData().getDepth()));
        et_exposedstratumcount.setText(StringUtil.isNull(bean.getData().getExposedstratumcount()));
        et_eqeventcount.setText(StringUtil.isNull(bean.getData().getEqeventcount()));
        et_latesteqperoidest.setText(StringUtil.isNull(bean.getData().getLatesteqperoidest()));
        et_latesteqperoider.setText(StringUtil.isNull(bean.getData().getLatesteqperoider()));
        et_collectedsamplecount.setText(StringUtil.isNull(bean.getData().getCollectedsamplecount()));
        et_samplecount.setText(StringUtil.isNull(bean.getData().getSamplecount()));
        et_datingsamplecount.setText(StringUtil.isNull(bean.getData().getDatingsamplecount()));
        et_commentinfo.setText(StringUtil.isNull(bean.getData().getCommentInfo()));
        photoRecycleBuild.setHttpUrl(bean.getData().getExtends7());
    }

    private TanCaodianDbEntity tanCaodianDbEntity;

    private void setDetail(TanCaodianDbEntity bean) {
        this.tanCaodianDbEntity = bean;
        etProvince.setText(StringUtil.isNull(bean.getProvince()));
        etCity.setText(StringUtil.isNull(bean.getCity()));
        etArea.setText(StringUtil.isNull(bean.getArea()));
        etLat.setText(bean.getLat());
        etLon.setText(bean.getLon());
        etBuildingAddress.setText(StringUtil.isNull(bean.getTown()));

        etTcid.setText(StringUtil.isNull(bean.getId()));
        et_name.setText(StringUtil.isNull(bean.getName()));
        et_elevation.setText(StringUtil.isNull(bean.getElevation()));
        et_trenchdip.setText(StringUtil.isNull(bean.getTrenchdip()));
        et_lastangle.setText(StringUtil.isNull(bean.getLastangle()));
        et_photoviewingto.setText(StringUtil.isNull(bean.getPhotoviewingtoName()));
        et_collectedtrenchsource.setText(StringUtil.isNull(bean.getCollectedtrenchsource()));
        etGeologysvyprojectid.setText(StringUtil.isNull(bean.getGeologysvyprojectid()));
        etFieldid.setText(StringUtil.isNull(bean.getFieldid()));
        etTargetfaultid.setText(StringUtil.isNull(bean.getTargetfaultid()));
        tv_targetfaultsource.setText(StringUtil.isNull(bean.getTargetfaultsource()));
        tv_targetfaultsource.setText(StringUtil.isNull(bean.getTargetfaultsourceName()));
        et_targetfaultname.setText(StringUtil.isNull(bean.getTargetfaultname()));
        tv_trenchsource.setText(StringUtil.isNull(bean.getTrenchsourceName()));
        et_locationname.setText(StringUtil.isNull(bean.getLocationname()));
        et_geomophenv.setText(StringUtil.isNull(bean.getGeomophenv()));
        et_photoAiid.setText(StringUtil.isNull(bean.getPhotoAiid()));
        et_photographer.setText(StringUtil.isNull(bean.getPhotographer()));
        et_length.setText(StringUtil.isNull(bean.getLength()));
        et_width.setText(StringUtil.isNull(bean.getWidth()));
        et_depth.setText(StringUtil.isNull(bean.getDepth()));
        et_exposedstratumcount.setText(StringUtil.isNull(bean.getExposedstratumcount()));
        et_eqeventcount.setText(StringUtil.isNull(bean.getEqeventcount()));
        et_latesteqperoidest.setText(StringUtil.isNull(bean.getLatesteqperoidest()));
        et_latesteqperoider.setText(StringUtil.isNull(bean.getLatesteqperoider()));
        et_collectedsamplecount.setText(StringUtil.isNull(bean.getCollectedsamplecount()));
        et_samplecount.setText(StringUtil.isNull(bean.getSamplecount()));
        et_datingsamplecount.setText(StringUtil.isNull(bean.getDatingsamplecount()));
        et_commentinfo.setText(StringUtil.isNull(bean.getCommentInfo()));
        if (!TextUtils.isEmpty(bean.getExtends7())) {
            String[] arr = bean.getExtends7().split(",");
            List<Uri> list = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                File file = new File(arr[i]);
                Uri uri = Uri.fromFile(file);
                list.add(uri);
            }
            photoRecycleBuild.updataAdapter(list);
        }
    }

    public ArrayList<AddressBean> parseData(String result) {//Gson 解析
        ArrayList<AddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), AddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
